package cn.tedu.jdbc;

import java.sql.*;
import java.util.ResourceBundle;

/**
 * 第一次使用JDBC完成查询操作
 */
public class JDBCTest05 {
    public static void main(String[] args) {
        Statement stmt = null;
        Connection conn = null;
        ResultSet rs = null;
        //1.注册驱动
        ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
        String driver = bundle.getString("driver");
        String url = bundle.getString("url");
        String user = bundle.getString("user");
        String password = bundle.getString("password");

        try {
            Class.forName(driver);
            //2.获取连接
            conn = DriverManager.getConnection(url, user, password);
            System.out.println("connection=" + conn);

            //3.获取数据库操作对象
            stmt = conn.createStatement();
            System.out.println("statement=" + stmt);

            //4.执行sql语句
//            String sql = "select * from t_user";
            String sql = "select realname,id,name,password from t_user";
            rs = stmt.executeQuery(sql);

            //5.处理查询结果集
            //以下获取方式是通过下标获取的，列下标从1开始
            boolean hasNext = rs.next();
            /*if (hasNext){
                String realname = resultSet.getString(1);
                String id = resultSet.getString(2);
                String name = resultSet.getString(3);
                String pwd = resultSet.getString(4);
                System.out.println(realname + "\t" + id + "\t" + name + "\t" + pwd + "\t" );
            }*/
            while(rs.next()){
                String s1 = rs.getString(1);
                String s2 = rs.getString(2);
                String s3 = rs.getString(3);
                String s4 = rs.getString(4);
                System.out.println(s1 + "\t" + s2 + "\t" + s3 + "\t" + s4 + "\t" );
            }

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }finally {
            //6.释放资源
            if (conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (stmt != null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
